import requests
import csv

f = open('data.csv', mode='w', encoding='utf-8', newline='')
csv_writer = csv.DictWriter(f, fieldnames=[
    '排行',
    '电影名字',
    '累计票房',
    '平均售价',
    '均场人数',
    '上映日期'
])
csv_writer.writeheader()

url = 'https://ys.endata.cn/enlib-api/api/home/getrank_mainland.do'

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36'
}
data = {
    'r': '0.37781609368449676',
    'top': '100',
    'type': '0'
}
resp = requests.post(url=url, headers=headers, data=data)
json_data = resp.json()

table0 = json_data['data']['table0']
# print(len(table0))
for item in table0:
    Irank = item['Irank']  # 排名
    MovieName = item['MovieName']  # 电影名字
    BoxOffice = item['BoxOffice']  # 累计票房
    AvgBoxOffice = item['AvgBoxOffice']  # 平均售价
    AvgAudienceCount = item['AvgAudienceCount']  # 均场人数
    ReleaseTime = item['ReleaseTime']  # 上映日期
    dic = {
        '排行': Irank,
        '电影名字': MovieName,
        '累计票房': BoxOffice,
        '平均售价': AvgBoxOffice,
        '均场人数': AvgAudienceCount,
        '上映日期': ReleaseTime
    }
    csv_writer.writerow(dic)
    print(Irank, MovieName, BoxOffice, AvgBoxOffice, AvgAudienceCount, ReleaseTime)
